//
//  AppDelegate.m
//  bgms_d
//
//  Created by lachesis-zhu on 03/07/2017.
//  Copyright © 2017 lachesis-zhu. All rights reserved.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "LXTabBarController.h"
#import "LXLoginVC.h"
#import <RealReachability/RealReachability.h>
#import "LXAlertTimer.h"
#import "LXLoginVC.h"
#import "EasyTextGlobalConfig.h"
#import "EasyLoadingGlobalConfig.h"

NSString *NTESNotificationLogout = @"NTESNotificationLogout";

@interface AppDelegate ()

@end

@implementation AppDelegate


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    [self onCheckVersion];
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    [self setupLoginViewController];
    
    EasyLoadingGlobalConfig *LoadingConfig = [EasyLoadingGlobalConfig shared];
    LoadingConfig.LoadingType = LoadingAnimationTypeFade ;
    LoadingConfig.bgColor = [UIColor colorWithHexString:@"efefef"];
    
    return YES;
}


-(void)applicationDidTimeout:(NSNotification *)notif {
    NSLog (@"超时要进行的操作");
    //[self setupLoginViewController];
    //[[NSNotificationCenter defaultCenter] removeObserver:self name:kApplicationDidTimeoutNotification object:nil];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    NSLog(@"应用程序将要进入非活动状态，即将进入后台");
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    UIBackgroundTaskIdentifier taskID = [application beginBackgroundTaskWithExpirationHandler:^{
        
    }];
    
    if (taskID != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:taskID];
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    application.applicationIconBadgeNumber = 0;
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{

}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{

}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    return YES;
}

#pragma mark version Check
- (void)onCheckVersion
{
    NSString *urlStr = @"https://itunes.apple.com/lookup?id=1308190408";
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:req delegate:self];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    //NSLog(@"当前的版本是 %@", currentVersion);
    
    NSError *error;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    NSDictionary *appInfo = (NSDictionary *)jsonObject;
    NSArray *infoArray = [appInfo objectForKey:@"results"];
    if ([infoArray count]) {
        NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
        NSString *appStoreVersion = [releaseInfo objectForKey:@"version"];
        if (![appStoreVersion isEqualToString:currentVersion]) {
            NSMutableArray *appStoreVersionArray = [[NSMutableArray alloc] initWithArray:[appStoreVersion componentsSeparatedByString:@"."]];
            NSMutableArray *currentVersionArray = [[NSMutableArray alloc] initWithArray:[currentVersion componentsSeparatedByString:@"."]];
            if (appStoreVersionArray.count != currentVersionArray.count) {
                NSInteger maxCount = appStoreVersionArray.count > currentVersionArray.count ? appStoreVersionArray.count : currentVersionArray.count;
                NSInteger appStoreLength = appStoreVersionArray.count;
                for (NSInteger i = appStoreLength; i < maxCount; i ++) {
                    [appStoreVersionArray addObject:@"0"];
                }
                NSInteger currentLength = currentVersionArray.count;
                for (NSInteger i = currentLength; i < maxCount; i ++) {
                    [currentVersionArray addObject:@"0"];
                }
            }
            NSString *newAppStore = @"";NSString *newCurrent = @"";
            for (int i = 0; i < appStoreVersionArray.count; i ++) {
                newAppStore = [appStoreVersionArray objectAtIndex:i];
                newCurrent = [currentVersionArray objectAtIndex:i];
                if ([newAppStore integerValue] > [newCurrent integerValue]) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"更新" message:@"有新的版本更新，是否前往更新？" delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:@"更新", nil];
                    alert.tag = 10000;
                    [alert show];
                    break;
                } else if ([newAppStore integerValue] < [newCurrent integerValue]) {
                    break;
                }
            }
        } else {
            
        }
    }
}

- (void)setupLoginViewController
{
    LXLoginVC *loginVC = [[LXLoginVC alloc] init];
    LXThemeColorNavigationController *themeNav = [[LXThemeColorNavigationController alloc] initWithRootViewController:loginVC];
    self.window.rootViewController = themeNav;

//    LXTabBarController *vc = [[LXTabBarController alloc] init];
//    [[UIApplication sharedApplication].delegate window].rootViewController = vc;
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "operation11.ZYMusicPlayer" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"ZYFPlayer" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"ZYFPlayer.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}
@end
